package org.csu.onlineedubackend.controller;

import org.csu.onlineedubackend.dto.OAuthUserInfoDTO;
import org.csu.onlineedubackend.result.CommonResponse;
import org.csu.onlineedubackend.result.ResponseCode;
import org.csu.onlineedubackend.service.OAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.RedirectView;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * OAuth第三方登录控制器
 */
@RestController
@RequestMapping("/api/oauth")
@CrossOrigin(origins = "*", maxAge = 3600)
public class OAuthController {

    @Autowired
    private OAuthService oauthService;

    @Value("${oauth.gitee.client_id}")
    private String giteeClientId;

    @Value("${oauth.gitee.client_secret}")
    private String giteeClientSecret;

    @Value("${oauth.gitee.redirect_uri}")
    private String giteeRedirectUri;

    @Value("${frontend.url}")
    private String frontendUrl;

    /**
     * 跳转到Gitee授权页面
     */
    @GetMapping("/gitee/login")
    public RedirectView giteeLogin() {
        // 构建Gitee授权URL
        String giteeAuthUrl = "https://gitee.com/oauth/authorize" +
                "?client_id=" + giteeClientId +
                "&redirect_uri=" + giteeRedirectUri +
                "&response_type=code" +
                "&scope=user_info";

        // 重定向到Gitee授权页面
        return new RedirectView(giteeAuthUrl);
    }

    /**
     * 处理Gitee回调
     */
    @GetMapping("/gitee/callback")
    public RedirectView giteeCallback(@RequestParam("code") String code) {
        try {
            // 获取access_token
            String accessToken = oauthService.getGiteeAccessToken(code);
            if (accessToken == null) {
                // 授权失败，重定向回前端并显示错误
                String errorMessage = URLEncoder.encode("获取授权令牌失败", StandardCharsets.UTF_8);
                return new RedirectView(frontendUrl + "/#/login?error=" + errorMessage);
            }

            // 获取用户信息
            OAuthUserInfoDTO userInfo = oauthService.getGiteeUserInfo(accessToken);
            if (userInfo == null) {
                // 获取用户信息失败，重定向回前端并显示错误
                String errorMessage = URLEncoder.encode("获取用户信息失败", StandardCharsets.UTF_8);
                return new RedirectView(frontendUrl + "/#/login?error=" + errorMessage);
            }

            // 处理登录或注册
            Map<String, Object> loginResult = oauthService.loginOrRegisterGiteeUser(userInfo);
            
            // 检查是否有错误
            if (loginResult.containsKey("error")) {
                // 用户不存在，重定向回前端并显示错误
                String loginName = (String) loginResult.get("loginName");
                String errorMessage = URLEncoder.encode("用户" + loginName + "不存在，请先注册", StandardCharsets.UTF_8);
                return new RedirectView(frontendUrl + "/#/login?error=" + errorMessage);
            }

            // 从登录结果中获取必要的参数
            // Map<String, Object> saTokenInfo = (Map<String, Object>) loginResult.get("saTokenInfo");
            // String tokenValue = saTokenInfo.get("tokenValue").toString();
            cn.dev33.satoken.stp.SaTokenInfo saTokenInfo = (cn.dev33.satoken.stp.SaTokenInfo) loginResult.get("saTokenInfo");
            String tokenValue = saTokenInfo.getTokenValue();
            String username = loginResult.get("username").toString();
            String userId = loginResult.get("userId").toString();
            String role = loginResult.get("role").toString();
            String name = loginResult.get("name").toString();

            // 构建重定向URL
            StringBuilder redirectUrlBuilder = new StringBuilder(frontendUrl);
            redirectUrlBuilder.append("/#/login");  // 添加哈希符号匹配前端路由模式
            redirectUrlBuilder.append("?token=").append(URLEncoder.encode(tokenValue, StandardCharsets.UTF_8));
            redirectUrlBuilder.append("&username=").append(URLEncoder.encode(username, StandardCharsets.UTF_8));
            redirectUrlBuilder.append("&userId=").append(userId);
            redirectUrlBuilder.append("&role=").append(role);
            redirectUrlBuilder.append("&name=").append(URLEncoder.encode(name, StandardCharsets.UTF_8));
            
            String redirectUrl = redirectUrlBuilder.toString();
            
            // 记录重定向URL便于调试
            System.out.println("第三方登录重定向URL: " + redirectUrl);

            // 重定向回前端
            return new RedirectView(redirectUrl);
        } catch (Exception e) {
            e.printStackTrace();
            // 发生异常，重定向回前端并显示错误
            String errorMessage;
            try {
                errorMessage = URLEncoder.encode(e.getMessage(), StandardCharsets.UTF_8);
            } catch (Exception ex) {
                errorMessage = "error-encoding-failed";
            }
            return new RedirectView(frontendUrl + "/#/login?error=" + errorMessage);
        }
    }
} 